package com.ebt.m.customer.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ebt.m.R;
import com.ebt.m.commons.buscomponent.permission.RxPermissions;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.customer.adapter.AdapterContact;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.event.CustomerSelectAllStringEvent;
import com.ebt.m.customer.event.EventCustomerListRefresh;
import com.ebt.m.customer.item.Contact;
import com.ebt.m.customer.service.FetchCustomerService;
import com.ebt.m.customer.util.CustomerRecorder;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.customer.view.VerticalStraightTextView;
import com.ebt.m.data.CustomerData;
import com.ebt.m.data.DatabaseManager;
import com.ebt.m.widget.MaterialishProgressDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.tendcloud.tenddata.TCAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ActivityCustomerImport extends Activity {

    private static final String TEXT_SELECT_ALL = "全选";
    private static final String TEXT_UNSELECT_ALL = "取消全选";

    //自定义右侧的列表view
    private VerticalStraightTextView fragment_customer_import_v_alphabet;
    private TextView fragment_customer_import_tv_title;
    private TextView fragment_customer_import_tv_toast;
    private ListView fragment_customer_import_lv_content;
    private View fragment_customer_import_btn_cancel;
    private TextView fragment_customer_import_btn_import;
    private View fragment_customer_import_tv_empty;
    private RelativeLayout rl_import_all;
    private TextView tv_import_all;

    private AdapterContact adapter;
    private List<Contact> mContacts = new ArrayList<>();
    private int contactsSize = 0;
    private String alphabet = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    //上次第一个可见元素，用于滚动时记录标识。
    private int lastFirstVisibleItem = -1;

    private HashMap<Integer, Integer> sectionToPosition = new HashMap();
    private RxPermissions rxPermissions;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initWindow();
        initViews();
        EventBus.getDefault().register(this);
        getPermissons();
    }

    private void getPermissons() {
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }
        rxPermissions.request(Manifest.permission.READ_CONTACTS)
                .subscribe(permission -> {
                    if (permission) {
                        refreshData();
                        setContactPassed();
                    } else {
                        finish();
                    }
                });
    }

    private void setContactPassed() {
        getWindow().getDecorView().postDelayed(new Runnable() {
            @Override
            public void run() {
                CustomerData cd = new CustomerData(ActivityCustomerImport.this);
                cd.setPassedName();
            }
        }, 1000);
    }

    private void refreshData() {
        if (sectionToPosition == null) {
            sectionToPosition = new HashMap<>();
        } else {
            sectionToPosition.clear();
        }
        showWaitProgressDialog();
        updateContentData();
    }

    private void updateContentData() {
        Observable
                .create(
                        new ObservableOnSubscribe<List<Contact>>() {
                            @Override
                            public void subscribe(ObservableEmitter<List<Contact>> observableEmitter) throws Exception {
                                observableEmitter.onNext(getContacts2());
                                observableEmitter.onComplete();
                            }
                        }
                )
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<List<Contact>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onComplete() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(List<Contact> contacts) {
                        if (contacts == null) {
                            contacts = new ArrayList<>();
                        }
                        contactsSize = contacts.size();
                        mContacts.clear();
                        mContacts.addAll(contacts);
                        adapter = new AdapterContact(ActivityCustomerImport.this, mContacts);
                        if (contactsSize > 0) {
                            setupContactsListView();
                            setAlpabetListener();
                        } else {
                            fragment_customer_import_v_alphabet.setVisibility(View.GONE);
                            fragment_customer_import_tv_title.setVisibility(View.GONE);
                            rl_import_all.setVisibility(View.GONE);
                            fragment_customer_import_tv_empty.setVisibility(View.VISIBLE);
                        }
                        dismissWaitProgressDialog();
                    }
                });
    }

    private List<Contact> getContacts2() {
        CustomerData cd = new CustomerData(this);
        return cd.getListOfContactForCustomerImport();
    }

    public void initViews() {
        setContentView(R.layout.activity_customer_import);
        fragment_customer_import_tv_title = (TextView) findViewById(R.id.fragment_customer_import_tv_title);
        fragment_customer_import_tv_toast = (TextView) findViewById(R.id.fragment_customer_import_tv_toast);
        fragment_customer_import_tv_empty = findViewById(R.id.fragment_customer_import_tv_empty);
        fragment_customer_import_v_alphabet = (VerticalStraightTextView) findViewById(R.id.fragment_customer_import_v_alphabet);
        fragment_customer_import_lv_content = (ListView) findViewById(R.id.fragment_customer_import_lv_content);
        fragment_customer_import_lv_content.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        fragment_customer_import_btn_cancel = findViewById(R.id.fragment_customer_import_btn_cancel);
        fragment_customer_import_btn_import = (TextView) findViewById(R.id.fragment_customer_import_btn_import);
        rl_import_all = (RelativeLayout) findViewById(R.id.rl_import_all);
        tv_import_all = (TextView) findViewById(R.id.tv_import_all);

        RxView.clicks(fragment_customer_import_btn_cancel)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    onBackPressed();
                });
        RxView.clicks(fragment_customer_import_btn_import)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    if (!NetUtils.isNetworkAvailable(this)) {
                        ToastUtil.showToast(getString(R.string.network_fail));
                        return;
                    }
                    importContacts();
                    TCAgent.onEvent(ActivityCustomerImport.this, "import_customer_batch");
                });
        RxView.clicks(tv_import_all)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    if (mContacts != null) {
                        int size = adapter.getCount();
                        int checkedSize = 0;
                        for (int i = 0; i < size; i++) {
                            if (fragment_customer_import_lv_content.isItemChecked(i)) {
                                checkedSize++;
                            } else {
                                break;
                            }
                        }
                        if (checkedSize < size) {
                            //全选
                            for (int i = 0; i < size; i++) {
                                fragment_customer_import_lv_content.setItemChecked(i, true);
                            }
                            tv_import_all.setText(TEXT_UNSELECT_ALL);
                        } else {
                            //全不选
                            for (int i = 0; i < size; i++) {
                                fragment_customer_import_lv_content.setItemChecked(i, false);
                            }
                            tv_import_all.setText(TEXT_SELECT_ALL);
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    private DialogWaitProgress waitDialog = null;

    private void showWaitProgressDialog() {
        if (waitDialog == null) {
            waitDialog = new DialogWaitProgress(this);
        }
        if (waitDialog.isShowing()) {
            waitDialog.dismiss();
        }
        waitDialog.show();
    }

    private void dismissWaitProgressDialog() {
        if (waitDialog == null) {
            waitDialog = new DialogWaitProgress(this);
        }
        if (waitDialog.isShowing()) {
            waitDialog.dismiss();
        }
    }

    public void initWindow() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    /**
     * 为联系人ListView设置监听事件，根据当前的滑动状态来改变分组的显示位置，从而实现挤压动画的效果。
     */
    private void setupContactsListView() {

        fragment_customer_import_lv_content.setAdapter(adapter);
        fragment_customer_import_lv_content.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                adapter.notifyDataSetChanged();
                int size = adapter.getCount();
                int checkedSize = 0;
                for (int i = 0; i < size; i++) {
                    if (fragment_customer_import_lv_content.isItemChecked(i)) {
                        checkedSize++;
                    } else {
                        break;
                    }
                }
                if (checkedSize < size) {
                    EventBus.getDefault().post(new CustomerSelectAllStringEvent(true));
                } else {
                    EventBus.getDefault().post(new CustomerSelectAllStringEvent(false));
                }
            }
        });
        fragment_customer_import_lv_content.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                if (fragment_customer_import_tv_title.getVisibility() != View.VISIBLE) {
                    return;
                }

                int section = getSectionForPositionReal(firstVisibleItem);
                int nextSecPosition = getPositionForSectionReal(section + 1);

                if (firstVisibleItem != lastFirstVisibleItem) {
                    MarginLayoutParams params = (MarginLayoutParams) fragment_customer_import_tv_title.getLayoutParams();
                    params.topMargin = 0;
                    fragment_customer_import_tv_title.setLayoutParams(params);
                    fragment_customer_import_tv_title.setText(String.valueOf(alphabet.charAt(section)));
                }

                if (nextSecPosition == firstVisibleItem + 1) {
                    View childView = view.getChildAt(0);
                    if (childView != null) {
                        int titleHeight = fragment_customer_import_tv_title.getHeight();
                        int bottom = childView.getBottom();
                        MarginLayoutParams params = (MarginLayoutParams) fragment_customer_import_tv_title.getLayoutParams();
                        if (bottom < titleHeight) {
                            float pushedDistance = bottom - titleHeight;
                            params.topMargin = (int) pushedDistance;
                            fragment_customer_import_tv_title.setLayoutParams(params);
                        } else {
                            if (params.topMargin != 0) {
                                params.topMargin = 0;
                                fragment_customer_import_tv_title.setLayoutParams(params);
                            }
                        }
                    }
                }
                lastFirstVisibleItem = firstVisibleItem;
            }
        });
    }

    private MaterialishProgressDialog materialishProgressDialog;

    private void showMaterialishProgressDialog() {
        if (materialishProgressDialog == null) {
            materialishProgressDialog = new MaterialishProgressDialog
                    .Builder(this)
                    .setShowTitle(false)
                    .setShowButtons(false)
                    .setCancelable(false)
                    .setCanceledOnTouchOutside(false)
                    .setContentText("正在导入，可能要花费些时间，请耐心等待")
                    .create();
        }
        materialishProgressDialog.show();
    }

    private void dismissMaterialishProgressDialog() {
        if (materialishProgressDialog != null) {
            materialishProgressDialog.dismiss();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
    }

    private void importContacts() {
        long lastActiveTime = System.currentTimeMillis();
        SparseBooleanArray sab = fragment_customer_import_lv_content.getCheckedItemPositions();
        int size = sab.size();
        ArrayList<Contact> contactsWithCUuid = new ArrayList();
        if (size > 0) {
            StringBuffer sql_delete_customer_from_contact_for_ignoreToAdd = new StringBuffer();
            sql_delete_customer_from_contact_for_ignoreToAdd.append("DELETE FROM " + CustomerConstant.CustomerFromContact.TABLE_NAME
                    + " WHERE " + CustomerConstant.CustomerFromContact.UUID + "=?;");
            DatabaseManager dbManager = DatabaseManager.getInstance(ActivityCustomerImport.this);
            dbManager.open();
            SQLiteDatabase db = dbManager.getSqliteDatabase();
            SQLiteStatement statement_customer_from_contact_for_ignoreToAdd = db.compileStatement(sql_delete_customer_from_contact_for_ignoreToAdd.toString());
            db.beginTransaction();

            try {
                for (int i = 0; i < size; i++) {
                    int position = sab.keyAt(i);
                    boolean value = sab.valueAt(i);
                    if (value) {
                        Contact contact = mContacts.get(position);
                        if (contact.hasImported) {
                            continue;
                        }

                        //删除表中已有的“已忽略”数据
                        if (contact.hasIgnored) {
                            statement_customer_from_contact_for_ignoreToAdd.bindString(1, contact.customerFromContactUuid);
                            statement_customer_from_contact_for_ignoreToAdd.executeUpdateDelete();
                        }

                        contact.remarkUuid = UUID.randomUUID().toString() + "_remark";//作为网络返回数据的键值对
                        contact.lastActiveTime = lastActiveTime;
                        contactsWithCUuid.add(contact);
                    }
                }
                db.setTransactionSuccessful();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(ActivityCustomerImport.this, "联系人导入失败", Toast.LENGTH_SHORT).show();
            } finally {
                db.endTransaction();
            }
            dbManager.close();
        } else {
            Toast.makeText(ActivityCustomerImport.this, "未导入联系人", Toast.LENGTH_SHORT).show();
        }

        if (contactsWithCUuid.size() > 0) {
            showMaterialishProgressDialog();
            if (contactsWithCUuid.size() == 1) {
                CustomerRecorder.recordCustomers(getApplicationContext(), contactsWithCUuid, CustomerRecorder.CUSTOMER_ADDED, "导入客户");
            } else {
                CustomerRecorder.recordCustomersIntoOneRecord(getApplicationContext(), contactsWithCUuid,
                        CustomerRecorder.CUSTOMER_ADDED_INTO_ONE_RECORD);
                CustomerRecorder.recordEveryCustomers(getApplicationContext(), contactsWithCUuid,
                        CustomerRecorder.CUSTOMER_IMPORT_INTO_RECORDS);
            }
            Intent startIntent = new Intent(this, FetchCustomerService.class);
            startIntent.putExtra(CustomerConstant.SERVICE_FETCH_MODE, CustomerConstant.SERVICE_FETCH_CUSTOMER_IMPORT_OTHER);
            startIntent.putExtra(CustomerConstant.SERVICE_FETCH_CUSTOMER_IMPORT_OTHER_KEY, contactsWithCUuid);
            startService(startIntent);
        }
    }


    /**
     * 设置字母表上的触摸事件，根据当前触摸的位置结合字母表的高度，计算出当前触摸在哪个字母上。
     * 当手指按在字母表上时，展示弹出式分组。手指离开字母表时，将弹出式分组隐藏。
     */
    private void setAlpabetListener() {
        fragment_customer_import_v_alphabet.setOnTouchedCharListener(new VerticalStraightTextView.OnTouchedCharListener() {

            @Override
            public void onTouchedCharReleased(String releasedString, int releasedIndex) {
            }

            @Override
            public void onTouchedCharChanged(String releasedString, int releasedIndex, String pickedString, int pickedIndex) {
            }

            @Override
            public void onTouchedCharPicked(String pickedString, int pickedIndex) {
                String sectionLetterActionDown = String.valueOf(alphabet.charAt(pickedIndex));
                fragment_customer_import_tv_toast.setText(sectionLetterActionDown);
                fragment_customer_import_tv_toast.setVisibility(View.VISIBLE);
                int positionActionDown = getPositionForSectionReal(pickedIndex);
                fragment_customer_import_lv_content.setSelection(positionActionDown);
            }

            @Override
            public void onTouchedCharReleasedFinally(String releasedString, int releasedIndex) {
                fragment_customer_import_tv_toast.setVisibility(View.GONE);
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        sectionToPosition.clear();
        mContacts.clear();
        contactsSize = 0;
        dismissMaterialishProgressDialog();
    }

    public int getSectionForPositionReal(int position) {
        char c = mContacts.get(position).sortKeyChar;
        for (int i = 0; i < CustomerConstant.Sort.CHARS_ALPHA_SIZE; i++) {
            if (c == CustomerConstant.Sort.CHARS_ALPHA[i]) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSectionReal(int section) {
        if (section >= 27) {
            return -1;
        }
        Integer p = sectionToPosition.get(section);
        if (p != null) {
            return p;
        }

        char c = CustomerConstant.Sort.CHARS_ALPHA[section];

        int size = contactsSize;
        for (int i = 0; i < size; i++) {
            if (mContacts.get(i).sortKeyChar >= c) {
                sectionToPosition.put(section, i);
                return i;
            }
        }
        return -1;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CustomerSelectAllStringEvent event) {
        if (event == null) {
            return;
        }
        if (event.selectAll) {
            tv_import_all.setText(TEXT_SELECT_ALL);
        } else {
            tv_import_all.setText(TEXT_UNSELECT_ALL);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCustomerListRefresh event) {
        onBackPressed();
    }

}